package com.fjzn.detect.security;

import com.alibaba.fastjson.JSON;
import com.fjzn.detect.core.utils.http.ServletUtils;
import com.fjzn.detect.core.result.ResponseResult;
import com.fjzn.detect.service.jwt.TokenService;
import com.fjzn.detect.service.security.LoginUser;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author helloworld
 */
@Log4j2
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{

    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser))
        {
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            log.info("{}用户登出，登出信息：{}",loginUser.getUsername(),loginUser);
        }
        ServletUtils.renderString(response, JSON.toJSONString(ResponseResult.success()));
    }
}
